using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Web;

namespace Q.Framework.Utility
{
    public static class AssemblyUtility
    {
       public static Assembly GetApplicationAssembly()
        {
            // Try the EntryAssembly, this doesn't work for ASP.NET classic pipeline (untested on integrated)
            Assembly ass = Assembly.GetEntryAssembly();

            // Look for web application assembly
            HttpContext ctx = HttpContext.Current;
            if (ctx != null)
                ass = GetWebApplicationAssembly(ctx);

            // Fallback to executing assembly
            return ass ?? (Assembly.GetExecutingAssembly());
        }

        private static Assembly GetWebApplicationAssembly(HttpContext context)
        {
            IHttpHandler handler = context.CurrentHandler;
            if (handler == null) return null;

            Type type = handler.GetType();
            while (type != null && type != typeof(object) && type.Namespace == "ASP")
                type = type.BaseType;

            return type.Assembly;
        }
    }
}